package com.example.demo.controllers;

import com.example.demo.models.RegionStats;
import com.example.demo.services.CoronaVirusDataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class HomeController {

    private final CoronaVirusDataService coronaVirusDataService;

    public HomeController(CoronaVirusDataService coronaVirusDataService) {
        this.coronaVirusDataService = coronaVirusDataService;
    }

    @GetMapping("/")
    public String select(Model model,String country) {
        List<RegionStats> allStats;
        if(country == null)
            allStats = coronaVirusDataService.getAllRegionStats();
        else
            allStats = coronaVirusDataService.getAllRegionStats()
                                               .parallelStream()
                                                .filter(locationStats -> locationStats.getCountry().equals(country))
                                                 .collect(Collectors.toUnmodifiableList());
        model.addAttribute("country",country);

        int totalReportedCases = allStats.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int totalNewCases = allStats.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();
//        Map<String,long> totaldatenum =allStats.parallelStream().

        model.addAttribute("RegionStats",allStats);
        model.addAttribute("totalReportedCases",totalReportedCases);

        model.addAttribute("totalNewCases",totalNewCases);


        model.addAttribute("localDate", LocalDate.now());

        return "index";
    }



}
